<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="js/jquery-3.4.1.js"></script>
    <script src="js/axios.js"></script>
    <script>        
      //axios的请求拦截,在发起请求前会执行此函数，
    //req是请求对象
    axios.interceptors.request.use(function(req) {
      let userStr = sessionStorage.getItem('user')
      let user = JSON.parse(userStr)
      let token = user.token
      let username = user.username
      $('.title').html("欢迎您："+username)
      //给请求对象添加请求头信息，Authorization = token
      req.headers['Authorization'] = token
      //拦截放行
      return req
    })

    async function getGoodsList(url, pagenum, pagesize) {
      let { data: res } = await axios.get(url, { params: { pagenum, pagesize } })
      let goodsList =  res.data.goods
      appendGoods(goodsList)
    }

    //拼接商品到页面
    function appendGoods(goodsList) {
      let app = $('#app')
      let ul = $('<ul></ul>')
      for (let i = 0, len = goodsList.length; i < len; i++) {
        let li = `
          <li><span>${goodsList[i].goods_id}</span>----<span>${goodsList[i].goods_name}</span>----<span>${'$' + goodsList[i].goods_price}</span></li>
        `
        ul.append(li)
      }
      app.append(ul)
    }

    $(function() {
      //请求所有的商品列表数据
      try {
        getGoodsList(`http://192.168.102.5:8888/api/private/v1/goods`, 1, 20)
      } catch (e) {
        console.log(e)
      }
    })
    </script>
</head>
<body>
    <div id="app">
        <h3 class="title"></h3>
    </div>
</body>
</html>